import threading
from dataclasses import dataclass
from datetime import datetime
from time import sleep
from typing import List

from flask import Flask, render_template, request, redirect

import rpi
import manager

app = Flask(__name__)


def loop():
    while True:
        now = datetime.now()
        minute = now.hour * 60 + now.minute
        for item in manager.schedule:
            if item['time'] == minute:
                rpi.feed(item['length'])
        seconds = 60 - datetime.now().second
        sleep(seconds)


@dataclass
class Item:
    id: int
    time: str
    length: float


@app.route('/')
def index():
    items: List[Item] = []

    for (i, item) in enumerate(manager.schedule):
        items.append(Item(
            i,
            str(item['time'] // 60 % 24).zfill(2) + ':' + str(item['time'] % 60).zfill(2),
            item['length']
        ))

    return render_template('index.html', items=items)


@app.route("/add", methods=['GET', 'POST'])
def add_page():
    if request.method == 'POST':
        time = str(request.form.get('time')).split(':')
        manager.add_schedule(
            int(time[0]) * 60 + int(time[1]),
            float(request.form.get('length'))
        )
        return redirect("/", code=302)
    return render_template('add.html')


@app.route("/edit", methods=['GET', 'POST'])
def edit_page():
    if request.method == 'POST':
        time = str(request.form.get('time')).split(':')
        manager.edit_schedule(
            int(request.form.get('id')),
            int(time[0]) * 60 + int(time[1]),
            float(request.form.get('length'))
        )
        return redirect("/", code=302)

    schedule_id = int(request.args.get('id'))
    schedule = manager.schedule[schedule_id]
    time = str(schedule['time'] // 60 % 24).zfill(2) + ':' + str(schedule['time'] % 60).zfill(2)

    return render_template('edit.html', id=schedule_id, time=time, length=schedule['length'])


@app.route("/delete", methods=['GET'])
def delete():
    schedule_id = int(request.args.get('id'))
    manager.delete_schedule(schedule_id)
    return redirect("/", code=302)


@app.route("/feed", methods=['POST'])
def feed_now():
    rpi.feed(float(request.form.get('length')))
    return redirect("/", code=302)


if __name__ == '__main__':
    rpi.init()
    threading.Thread(target=app.run, args=['0.0.0.0', 80, False], daemon=True).start()
    loop()
